<template>
  <view class="reserve-container">
    <!-- 套餐信息 -->
    <view class="package-info">
      <text class="title">预约信息</text>
      <view class="info-item">
        <text class="label">套餐名称</text>
        <text class="value">{{ packageName }}</text>
      </view>
      <view class="info-item">
        <text class="label">预约时间</text>
        <picker mode="date" :value="reserveDate" :start="startDate" :end="endDate" @change="handleDateChange">
          <view class="picker-value">{{ reserveDate || '请选择预约时间' }}</view>
        </picker>
      </view>
      <view class="info-item">
        <text class="label">预约人</text>
        <input type="text" v-model="userName" placeholder="请输入预约人姓名" class="input"/>
      </view>
      <view class="info-item">
        <text class="label">手机号码</text>
        <input type="number" v-model="phone" placeholder="请输入手机号码" class="input"/>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-bar">
      <view class="price-info">
        <text class="label">总计：</text>
        <text class="price">¥{{ packagePrice }}</text>
      </view>
      <button class="submit-btn" @click="handleSubmit" :disabled="!isFormValid">提交预约</button>
    </view>

    <!-- 支付二维码弹窗 -->
    <view v-if="showQRCode" class="qrcode-popup-overlay" @click="closeQRCode">
      <view class="qrcode-popup" @click.stop>
        <view class="popup-header">
          <text class="popup-title">使用手机微信扫码支付</text>
          <text class="close-btn" @click="closeQRCode">×</text>
        </view>
        <view class="qrcode-content">
          <view v-if="qrcodeUrl" class="qrcode-wrapper">
            <image :src="qrcodeUrl" mode="aspectFit" class="qrcode-image"></image>
            <text class="price">¥{{ packagePrice }}</text>
          </view>
          <text v-else class="loading">正在生成支付二维码...</text>
        </view>
        <text class="tip">请使用微信扫一扫完成支付</text>
        <text class="order-number">订单号：{{ orderId }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import { orderApi } from '@/api/order'

export default {
  data() {
    return {
      packageId: null,
      packageName: '',
      packagePrice: 0,
      reserveDate: '',
      userName: '',
      phone: '',
      qrcodeUrl: '',
      orderId: null,
      payCheckTimer: null,
      startDate: this.getStartDate(),
      endDate: this.getEndDate(),
      isSubmitting: false,
      showQRCode: false
    }
  },

  computed: {
    isFormValid() {
      return this.reserveDate && 
             this.userName && 
             this.userName.trim().length >= 2 &&
             this.phone && 
             /^1[3-9]\d{9}$/.test(this.phone)
    }
  },

  onLoad(options) {
    if (options.id && options.name && options.price) {
      this.packageId = parseInt(options.id)
      this.packageName = decodeURIComponent(options.name)
      this.packagePrice = parseFloat(options.price)
    } else {
      uni.showToast({
        title: '参数错误',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  },

  onUnload() {
    this.clearPayCheckTimer()
  },

  methods: {
    // 获取可选开始日期（明天）
    getStartDate() {
      const date = new Date()
      date.setDate(date.getDate() + 1)
      return date.toISOString().split('T')[0]
    },

    // 获取可选结束日期（三个月后）
    getEndDate() {
      const date = new Date()
      date.setMonth(date.getMonth() + 3)
      return date.toISOString().split('T')[0]
    },

    handleDateChange(e) {
      this.reserveDate = e.detail.value
    },

    validateForm() {
      if (!this.reserveDate) {
        uni.showToast({
          title: '请选择预约时间',
          icon: 'none'
        })
        return false
      }
      if (!this.userName || this.userName.trim().length < 2) {
        uni.showToast({
          title: '请输入正确的姓名',
          icon: 'none'
        })
        return false
      }
      if (!this.phone || !/^1[3-9]\d{9}$/.test(this.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return false
      }
      return true
    },

    // 提交预约
    async handleSubmit() {
      if (this.isSubmitting) return
      if (!this.validateForm()) return

      this.isSubmitting = true
      uni.showLoading({
        title: '提交中...',
        mask: true
      })

      try {
        const orderRes = await orderApi.createSetMealOrder({
          setmealId: this.packageId,
          orderDate: this.reserveDate,
          setmealName: this.packageName,
          orderName: this.userName,
          phone: this.phone
        })

        if (orderRes.code === 200 && orderRes.data) {
          // 保存订单信息和二维码
          this.orderId = orderRes.data['Order number']
          // 直接使用base64图片数据
          this.qrcodeUrl = orderRes.data['QR code image']
          
          // 显示二维码弹窗
          this.showQRCode = true
          
          // 开始检查支付状态
          this.startCheckPayStatus()
        } else {
          throw new Error(orderRes.errorMessage || '预约失败')
        }
      } catch (error) {
        console.error('提交预约失败:', error)
        uni.showToast({
          title: error.message || '预约失败，请重试',
          icon: 'none'
        })
      } finally {
        this.isSubmitting = false
        uni.hideLoading()
      }
    },

    // 开始检查支付状态
    startCheckPayStatus() {
      this.clearPayCheckTimer()
      let checkCount = 0
      const maxChecks = 20 // 最大检查次数，与后端一致
      
      this.payCheckTimer = setInterval(async () => {
        try {
          checkCount++
          // 如果已经达到最大检查次数，直接停止
          if (checkCount >= maxChecks) {
            this.clearPayCheckTimer()
            this.handlePayTimeout()
            return
          }

          const res = await orderApi.checkPayStatus(this.orderId)
          console.log('支付状态检查结果:', res)
          
          // 根据后端返回判断状态
          if (res.code === 200 && res.errorMessage === 'SUCCESS') {
            // 支付成功
            this.handlePaymentSuccess()
          } else if (res.code === 400 && res.errorMessage === 'TIMEOUT') {
            // 支付超时
            this.clearPayCheckTimer()
            this.handlePayTimeout()
          }
        } catch (error) {
          console.error('检查支付状态失败:', error)
          // 出错时继续检查，直到达到最大次数
        }
      }, 3000) // 每3秒检查一次
    },

    // 处理支付超时
    handlePayTimeout() {
      uni.showModal({
        title: '支付提示',
        content: '支付状态查询超时，请重新发起支付。',
        showCancel: false,
        confirmText: '我知道了',
        success: () => {
          // 重置支付状态
          this.showQRCode = false
          this.qrcodeUrl = ''
          this.orderId = null
          // 返回上一页
          uni.navigateBack()
        }
      })
    },

    // 处理支付成功
    handlePaymentSuccess() {
      this.clearPayCheckTimer()
      this.showQRCode = false
      
      uni.showToast({
        title: '支付成功',
        icon: 'success'
      })

      // 延迟跳转到订单列表页
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/user/user'
        })
      }, 1500)
    },

    // 清除支付状态检查定时器
    clearPayCheckTimer() {
      if (this.payCheckTimer) {
        clearInterval(this.payCheckTimer)
        this.payCheckTimer = null
      }
    },

    // 关闭二维码弹窗
    closeQRCode() {
      uni.showModal({
        title: '提示',
        content: '确定要取消支付吗？',
        success: (res) => {
          if (res.confirm) {
            this.clearPayCheckTimer()
            this.showQRCode = false
          }
        }
      })
    }
  }
}
</script>

<style lang="scss">
.reserve-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 120rpx;

  .package-info {
    background: #fff;
    padding: 30rpx;
    margin: 20rpx;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

    .title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 30rpx;
      position: relative;
      padding-left: 20rpx;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 6rpx;
        height: 28rpx;
        background: #007AFF;
        border-radius: 3rpx;
      }
    }

    .info-item {
      display: flex;
      align-items: center;
      margin-bottom: 30rpx;
      padding: 20rpx;
      background: #f8f8f8;
      border-radius: 12rpx;

      .label {
        width: 160rpx;
        font-size: 28rpx;
        color: #666;
      }

      .value, .picker-value {
        flex: 1;
        font-size: 28rpx;
        color: #333;
      }

      .input {
        flex: 1;
        height: 60rpx;
        font-size: 28rpx;
        color: #333;
        padding: 0 20rpx;
      }

      .picker-value {
        height: 60rpx;
        line-height: 60rpx;
      }
    }
  }

  .qrcode-popup-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }

  .qrcode-popup {
    background: #fff;
    border-radius: 12rpx;
    width: 600rpx;
    padding: 30rpx;

    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;
      padding-bottom: 20rpx;
      border-bottom: 1px solid #eee;

      .popup-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }

      .close-btn {
        font-size: 48rpx;
        color: #999;
        padding: 0 20rpx;
        line-height: 1;
        cursor: pointer;

        &:active {
          opacity: 0.7;
        }
      }
    }

    .qrcode-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20rpx 0;

      .qrcode-wrapper {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-bottom: 20rpx;

        .qrcode-image {
          width: 320rpx;
          height: 320rpx;
          margin-bottom: 20rpx;
          background-color: #fff;
        }

        .price {
          font-size: 36rpx;
          color: #ff4d4f;
          font-weight: bold;
        }
      }

      .loading {
        font-size: 28rpx;
        color: #666;
        margin: 40rpx 0;
      }
    }

    .tip {
      font-size: 26rpx;
      color: #666;
      text-align: center;
      margin-top: 20rpx;
    }

    .order-number {
      font-size: 24rpx;
      color: #999;
      text-align: center;
      margin-top: 20rpx;
    }
  }

  .bottom-bar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    height: 100rpx;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 30rpx;
    box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.05);

    .price-info {
      display: flex;
      align-items: baseline;

      .label {
        font-size: 28rpx;
        color: #666;
      }

      .price {
        font-size: 36rpx;
        color: #ff4d4f;
        font-weight: bold;
      }
    }

    .submit-btn {
      width: 240rpx;
      height: 72rpx;
      line-height: 72rpx;
      background: #007AFF;
      color: #fff;
      font-size: 28rpx;
      border-radius: 36rpx;
      text-align: center;

      &:disabled {
        background: #ccc;
      }
    }
  }
}
</style> 